package com.sds.sweng.swat.miplatform.ui.design.parts.area.sub;

import java.util.List;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.swt.SWT;

import com.sds.sweng.swat.miplatform.ui.design.layouts.EasyGridData;
import com.sds.sweng.swat.miplatform.ui.design.layouts.FlowLayoutEx;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.SubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.SubAreaContainer;
import com.sds.sweng.swat.miplatform.ui.design.parts.MiplatformContainerPart;
import com.sds.sweng.swat.miplatform.ui.design.parts.area.AreaTemplatePart;

public class SubAreaContainerPart extends MiplatformContainerPart {

	protected IFigure createFigure() {
		Figure f = new Figure();
		f.setBackgroundColor(ColorConstants.white);
		f.setOpaque(true);

		FlowLayoutEx layout = new FlowLayoutEx(false);
		layout.setStretchMinorAxis(true);
		layout.setMajorSpacing(0);
		layout.setMinorSpacing(-1);

		f.setLayoutManager(layout);

		getParentLayout().setConstraint(f, EasyGridData.create(SWT.DEFAULT, SWT.DEFAULT));

		return f;
	}

	protected void createEditPolicies() {
		//installEditPolicy(EditPolicy.LAYOUT_ROLE, new TableFlowLayoutEditPolicy());
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new LayoutEditPolicy() {

			protected Command getMoveChildrenCommand(Request request) {
				return null;
			}

			protected Command getCreateCommand(CreateRequest request) {
				return null;
			}

			protected EditPolicy createChildEditPolicy(EditPart child) {
				return new NonResizableEditPolicy();
			}
		});
	}

	protected void refreshChildren() {
		super.refreshChildren();

		resizeFigure();
	}

	public void resizeFigure() {
		int width = 0;
		int height = 0;

		List subAreas = ((SubAreaContainer) getModel()).getChildren();
		for (int i=0;i<subAreas.size();i++) {
			SubArea subArea = (SubArea) subAreas.get(i);

			width = getAreaWidth();
			height += subArea.getHeight() == 0 ? SubArea.MODEL_HEIGHT : subArea.getHeight();
		}

		getFigure().setSize(getFigure().getSize().width, height);
		((SubAreaContainer) getModel()).setHeight(height);
		((AreaTemplatePart) getParent()).refreshAll();
	}

}
